package com.zhaiweijia.eurekazuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhaiweijia.vo.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //     pre：路由之前
        //     routing：路由之时
        //     post： 路由之后
        //     error：发送错误调用
        return "pre";
    }

    @Override
    public int filterOrder() {
        //值越小优先级越高
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //过滤器打开
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取当前上下文容器
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取当前请求http的url
        HttpServletRequest httpServletRequest = currentContext.getRequest();
        //获取url中的参数
        String token = httpServletRequest.getParameter("token");
        if(StringUtils.isEmpty(token)){
            currentContext.setSendZuulResponse(false);
            //401代码一般代表没有权限
            currentContext.setResponseStatusCode(401);
            try {
                HttpServletResponse httpServletResponse = currentContext.getResponse();
                httpServletResponse.setContentType("application/json;charset=utf-8");
                httpServletResponse.getWriter().write(JSON.toJSONString(ResultEntity.error("token为空")));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        log.info("成功了。。。。。。。。");
        return null;
    }
}
